package com.qdsg.ysg.doctor.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.FileProvider;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ainemo.sdk.otf.MakeCallResponse;
import com.ainemo.sdk.otf.NemoSDK;
import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseActivity;
import com.qdsg.ysg.doctor.base.BaseApplication;
import com.qdsg.ysg.doctor.eventbus.BillingStatusChangeEvent;
import com.qdsg.ysg.doctor.eventbus.WebSocket;
import com.qdsg.ysg.doctor.eventbus.WebSocketWrapper;
import com.qdsg.ysg.doctor.fw_permission.FloatWinPermissionCompat;
import com.qdsg.ysg.doctor.service.FloatingService;
import com.qdsg.ysg.doctor.ui.activity.checkout.CheckoutDetailActivity;
import com.qdsg.ysg.doctor.ui.activity.mine.SignatureActivity;
import com.qdsg.ysg.doctor.ui.activity.mine.SignatureSettingActivity;
import com.qdsg.ysg.doctor.ui.activity.prescription.AddCaseActivity;
import com.qdsg.ysg.doctor.ui.activity.prescription.AtyOrderMedicineDetailActivity;
import com.qdsg.ysg.doctor.ui.activity.prescription.PrescriptionListActivity;
import com.qdsg.ysg.doctor.ui.adapter.ChatAdapter;
import com.qdsg.ysg.doctor.ui.adapter.PhotoAdapter;
import com.qdsg.ysg.doctor.ui.dialog.ApplyPermissionDialog;
import com.qdsg.ysg.doctor.ui.dialog.Finish2Dialog;
import com.qdsg.ysg.doctor.ui.dialog.FinishDialog;
import com.qdsg.ysg.doctor.ui.dialog.ReceiveReferralDialog;
import com.qdsg.ysg.doctor.ui.dialog.RefundDialog;
import com.qdsg.ysg.doctor.ui.dialog.SelectPicModeDialog;
import com.qdsg.ysg.doctor.ui.dialog.SignatureDialog;
import com.qdsg.ysg.doctor.ui.widget.AudioRecorderButton;
import com.qdsg.ysg.doctor.ui.xylink.XyCallActivity;
import com.qdsg.ysg.doctor.util.PermissionsChecker;
import com.qdsg.ysg.doctor.util.SoftKeyboardUtil;
import com.qdsg.ysg.doctor.util.TimeUtil;
import com.qdsg.ysg.doctor.util.ToastUtil;
import com.qdsg.ysg.doctor.util.UIConstants;
import com.qdsg.ysg.doctor.util.UploadPictureUtil;
import com.qdsg.ysg.doctor.util.UriUtils;
import com.qdsg.ysg.doctor.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.exception.BusinessException;
import com.rest.response.AccountRespnonse;
import com.rest.response.AuthOauthVo;
import com.rest.response.BaseResponse;
import com.rest.response.ChatResponse;
import com.rest.response.OauthStatusResponse;
import com.rest.response.PicUploadResponse;
import com.rest.response.Prescription2Response;
import com.rest.response.RegistrationDetailResponse;
import com.rest.response.UserInfoBean;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LogUtil;

import static com.qdsg.ysg.doctor.ui.AddRegistrationActivity.REQUEST_GALLERY;
import static com.qdsg.ysg.doctor.ui.AddRegistrationActivity.REQUEST_OPEN_CAMERA;

/**
 * @Description: IM聊天界面
 * @Author: lzp
 * @CreateDate: 2023/10/19 12:27
 * @UpdateRemark: 更新说明
 */
public class ChatActivity extends BaseActivity {

    @BindView(R.id.chat_recyclerView)
    RecyclerView chat_recyclerView;
    @BindView(R.id.photo_recyclerView)
    RecyclerView photo_recyclerView;
    @BindView(R.id.btn_send)
    TextView btnSend;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_oneselfState)
    TextView tv_oneselfState;
    @BindView(R.id.btn_show)
    CheckBox btn_show;
    @BindView(R.id.top)
    LinearLayout top;
    @BindView(R.id.edt_content)
    EditText edt_content;
    @BindView(R.id.tv_patient_detail)
    TextView tv_patient_detail;
    @BindView(R.id.linearLayout)
    LinearLayout linearLayout;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R.id.tv_pass)
    TextView tv_pass;
    @BindView(R.id.tv_allergy)
    TextView tv_allergy;
    @BindView(R.id.tv_close)
    TextView tv_close;
    @BindView(R.id.tv_wait)
    LinearLayout tv_wait;
    @BindView(R.id.cl_bottom)
    ConstraintLayout bottom;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.tv_remain_time)
    TextView tv_remain_time;
    @BindView(R.id.remain_time_container)
    ConstraintLayout remain_time_container;
    @BindView(R.id.pass_container)
    LinearLayout pass_container;
    @BindView(R.id.allergy_container)
    LinearLayout allergy_container;
    @BindView(R.id.btn_end)
    TextView btn_end;
    @BindView(R.id.btn_yuyin)
    AudioRecorderButton btn_yuyin;
    @BindView(R.id.btn_add)
    ImageView btnAdd;
    @BindView(R.id.nested_scrollView)
    NestedScrollView nestedScrollView;
    @BindView(R.id.btn_add_photo)
    ImageView btnAddPhoto;
    @BindView(R.id.btn_video)
    ImageView btnVideo;
    @BindView(R.id.btn_prescription)
    ImageView btnPrescription;
    @BindView(R.id.btn_history)
    ImageView btnHistory;
    @BindView(R.id.btn_refund)
    ImageView btnRefund;
    @BindView(R.id.yuyin)
    ImageView yuyin;

    private PhotoAdapter adapter;
    private ChatAdapter chatAdapter;
    private final List<RegistrationDetailResponse.Photo> photoList = new ArrayList<>();
    private final List<ChatResponse.Message> messageList = new ArrayList<>();

    private String patientUserId, doctorUserId, doctorId, diagnoseId, patientId, createTime, acceptTime;
    private String patAccount, doctorName, patientName, pAge, doctorPicture, orderNumber;
    private int flag, type, chatFlag, diagnoseFlag, diagType, oFlag, readyFlag, orderStatus;

    private boolean isMeeting = false, isFromCloudList = false;
    MediaPlayer mediaPlayer;

    //原图像 URI
    private Uri imgUriOri;
    //原图像 路径
    private String imgPathOri;
    // 所需的全部权限
    private final String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
    };
    private final String[] VOICEPERMISSIONS = new String[]{
            Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private final String[] VIDEOPERMISSIONS = new String[]{
            Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA
    };
    private PermissionsChecker mPermissionsChecker; // 权限检测器


    private ProgressDialog dialog;
    private ProgressDialog dialogHuaWei;


    private int current = 1;
    private FinishDialog mFinishDialog;
    private Finish2Dialog mFinish2Dialog;
    private ReceiveReferralDialog receiveReferralDialog;

    private String videoAccount;
    private int businessType;

    private int playingIndex = -1;

    @Override
    protected int getLayoutResource() {
        return R.layout.aty_chat;
    }

    @Override
    protected void initViews() {
        LinearLayoutManager manager = new LinearLayoutManager(ChatActivity.this, LinearLayoutManager.HORIZONTAL, false);
        photo_recyclerView.setLayoutManager(manager);
        adapter = new PhotoAdapter(mContext, photoList);
        photo_recyclerView.setAdapter(adapter);

        initChatList();
        initListener();

        refreshLayout.setEnableLoadMore(false);
        mPermissionsChecker = new PermissionsChecker(mContext);
    }


    @Override
    protected void initData() {
        diagnoseId = getIntent().getStringExtra("diagnoseId");
        assert diagnoseId != null;
        Log.e("诊断id---", diagnoseId);
        oFlag = getIntent().getIntExtra("oFlag", 0);
        //如果是从云门诊开始诊断过来的，直接唤起视频
        isFromCloudList = getIntent().getBooleanExtra("isFromCloudList", false);
        readyFlag = getIntent().getIntExtra("readyFlag", 0);
        type = getIntent().getIntExtra("type", 0);
        getRegistrationDetail();
        getPatientAccount();
        EventBus.getDefault().register(this);
    }

    private void initListener() {
        btn_show.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                btn_show.setText("展开");
                pass_container.setVisibility(View.GONE);
                allergy_container.setVisibility(View.GONE);
            } else {
                btn_show.setText("收起");
                pass_container.setVisibility(View.VISIBLE);
                allergy_container.setVisibility(View.VISIBLE);
            }
        });

        refreshLayout.setOnRefreshListener(refreshLayout -> {
            current = 1;
            messageList.clear();
            getMessageList();
        });

        btn_yuyin.setAudioFinishRecorderListener((seconds, filePath) -> uploadVideo(filePath, (int) seconds));
        btn_yuyin.setOnLongClickMyListener(() -> {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            }
        });
        edt_content.setOnClickListener(v -> {
            nestedScrollView.postDelayed(() -> {
                nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
                edt_content.setFocusable(true);
                edt_content.setFocusableInTouchMode(true);
                edt_content.requestFocus();//获取焦点
            }, 500);
        });
        edt_content.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                sendTxtMessage();
            }
            return true;
        });
    }


    private void initChatList() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        chat_recyclerView.setLayoutManager(linearLayoutManager);
        chatAdapter = new ChatAdapter();
        chat_recyclerView.setAdapter(chatAdapter);
        chatAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (messageList.get(position).messageType == ChatResponse.IMAGE) {
                Bundle bundle = new Bundle();
                bundle.putString("url", messageList.get(position).src);
                bundle.putInt("type", 1);
                ChatActivity.this.startActivity(BigImageActivity.class, bundle);
            } else if (messageList.get(position).messageType == ChatResponse.AUDIO) {
                if (mediaPlayer != null) {
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.pause();
                        chatAdapter.notifyItemChanged(playingIndex + chatAdapter.getHeaderLayoutCount(), ChatAdapter.PLAYLOAD_PAUSE);
                        if (position != playingIndex) {
                            mediaPlayer.reset();
                            playSound(position);
                        }
                    } else {
                        mediaPlayer.reset();
                        playSound(position);
                    }
                } else {
                    mediaPlayer = new MediaPlayer();
                    playSound(position);
                }
            } else if (messageList.get(position).messageType == ChatResponse.PRESCRIPTION) {
                Bundle bundle = new Bundle();
                bundle.putString("orderId", messageList.get(position).prescription.orderId);
                startActivityForResult(AtyOrderMedicineDetailActivity.class, bundle, 10000);
            } else if (messageList.get(position).messageType == ChatResponse.CHECKOUT) {
                Bundle bundle = new Bundle();
                bundle.putString("checkId", messageList.get(position).checkList.dataId);
                startActivity(CheckoutDetailActivity.class, bundle);
            }
        });
    }

    @OnClick({R.id.btn_end, R.id.yuyin, R.id.btn_add, R.id.btn_add_photo, R.id.btn_video, R.id.btn_prescription, R.id.btn_history, R.id.btn_send, R.id.btn_refund})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_end:
                //结束问诊
                showLogoutDialog();
                break;
            case R.id.yuyin:
                checkServiceRunning(mContext);
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//                    switchTextAndAudio();
//                } else {
                // 缺少权限时, 进入权限配置页面
                if (mPermissionsChecker.lacksPermissions(VOICEPERMISSIONS)) {
                    checkVoicePermission();
                } else {
                    switchTextAndAudio();
//                    }
                }
                break;
            case R.id.btn_add:
                if (linearLayout.getVisibility() == View.GONE) {
                    linearLayout.setVisibility(View.VISIBLE);
                } else if (linearLayout.getVisibility() == View.VISIBLE) {
                    linearLayout.setVisibility(View.GONE);
                    edt_content.requestFocus();
                }
                nestedScrollView.postDelayed(() -> {
                    nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);
                }, 500);
                break;
            case R.id.btn_add_photo:
                checkServiceRunning(mContext);
                // 缺少权限时, 进入权限配置页面
                if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                    getPermission();
                } else {
                    showSelectHeadPicDialog();
                }
                break;
            case R.id.btn_video:
                checkServiceRunning(mContext);
                // 缺少权限时, 进入权限配置页面
                if (mPermissionsChecker.lacksPermissions(VIDEOPERMISSIONS)) {
                    checkPermission();
                } else {
                    startCall(videoAccount);
                }

                break;
            case R.id.btn_prescription:
                // 开处方
//                queryOauthStatus();
//                patientPrescriptionOrder();
                jump();
                break;
            case R.id.btn_history: //历史病例
                Bundle bundleHistory = new Bundle();
                bundleHistory.putString("patientId", patientId);
                bundleHistory.putString("fromWhere", "ChatActivity");
                startActivity(WebViewActivity.class, bundleHistory);
                break;
            case R.id.btn_send:
                sendTxtMessage();
                break;
            case R.id.btn_refund:
                showRefundDialog();
                break;
            default:
                break;
        }
    }

    public void switchTextAndAudio() {
        if (btn_yuyin.getVisibility() == View.GONE) {
            btn_yuyin.setVisibility(View.VISIBLE);
            yuyin.setImageResource(R.mipmap.jianpan);
            edt_content.setVisibility(View.GONE);
            SoftKeyboardUtil.hideKeyboard(edt_content);
        } else {
            btn_yuyin.setVisibility(View.GONE);
            yuyin.setImageResource(R.mipmap.yuyin);
            edt_content.setVisibility(View.VISIBLE);
            SoftKeyboardUtil.showSoftInput(edt_content);
        }
    }

    private void playSound(int position) {
        try {
            mediaPlayer.setDataSource(messageList.get(position).content);
            mediaPlayer.prepareAsync(); // 准备文件
            mediaPlayer.setOnPreparedListener(mp -> {
                // 装载完毕回调
                mediaPlayer.start();
                playingIndex = position;
                chatAdapter.notifyItemChanged(position + chatAdapter.getHeaderLayoutCount(), ChatAdapter.PLAYLOAD_SPEAKING);
            });
            mediaPlayer.setOnCompletionListener(mp -> {
                playingIndex = -1;
                chatAdapter.notifyItemChanged(position + chatAdapter.getHeaderLayoutCount(), ChatAdapter.PLAYLOAD_PAUSE);
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void sendTxtMessage() {
        checkServiceRunning(mContext);
        if (TextUtils.isEmpty(edt_content.getText().toString().trim())) {
            ToastUtil.showToast(mContext, "不能发送空白消息");
            return;
        }
        @SuppressLint("SimpleDateFormat") SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
        ChatResponse.Message message = new ChatResponse().new Message();
        String clientId = TimeUtil.getClientId();
        message.messageId = clientId;
        message.messageType = ChatResponse.TEXT;
        message.fromType = ChatResponse.DOCTOR;
        message.flag = ChatResponse.SNEDING;
        message.content = edt_content.getText().toString();
        message.sendTime = df.format(new Date());
        messageList.add(message);
        chatAdapter.addData(message);
        nestedScrollView.postDelayed(() -> {
            nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
            edt_content.setFocusable(true);
            edt_content.setFocusableInTouchMode(true);
            edt_content.requestFocus();//获取焦点
            edt_content.setText("");
        }, 500);
        WebSocket webSocket = new WebSocket.Builder().content(edt_content.getText().toString()).docId(doctorId).diagnoseId(diagnoseId).from(BaseApplication.currentUserId).to(patientUserId).msgType(0).eventFlag(1).clientId(clientId).build();
        EventBus.getDefault().postSticky(webSocket);
    }


    /**
     * 退费弹框
     */
    private void showRefundDialog() {
        RefundDialog refundDialog = RefundDialog.newInstance();
        refundDialog.setmListener(new RefundDialog.OnItemClickListener() {
            @Override
            public void onConfirm(String reason) {
                refund(reason);
            }

            @Override
            public void onCancel() {

            }
        });
        refundDialog.show(getSupportFragmentManager(), "refundDialog");
    }

    /**
     * 退费*
     *
     * @param reason 原因
     */
    public void refund(String reason) {
        RestProxy.getInstance().refund(orderNumber, reason, new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                ToastUtil.showToast(mContext, "退费成功");
                getRegistrationDetail();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }


    /*** 查询授权状态接口*/
    public void queryOauthStatus() {
        RestProxy.getInstance().queryOauthStatus(new Observer<OauthStatusResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(OauthStatusResponse oauthStatusResponse) {
                jump();
            }

            @Override
            public void onError(Throwable e) {
                if (e instanceof BusinessException) {
                    if (((BusinessException) e).errorCode == 2300) {
                        authOauth();
                    } else {
                        dismissProgressDialog();
                        ToastUtil.onError(mContext, e);
                    }
                }
            }

            @Override
            public void onComplete() {
                dismissProgressDialog();
            }
        });
    }

    public void jump() {
        Bundle bundle = new Bundle();
        if (diagType == 1) {//1：图文咨询
            bundle.putString("patientId", patientId);
            bundle.putSerializable("oneselfState", tv_oneselfState.getText().toString().trim());
            bundle.putString("diagnoseId", diagnoseId);
            startActivity(AddCaseActivity.class, bundle);
        }
        //3:云门诊
        if (diagType == 3) {
            if (diagnoseFlag == 0) {
                bundle.putString("diagnoseId", diagnoseId);
                startActivityForResult(PrescriptionListActivity.class, bundle, 10001);
            } else {
                bundle.putString("patientId", patientId);
                bundle.putString("diagnoseId", diagnoseId);
                startActivityForResult(AddCaseActivity.class, bundle, 10000);
            }
        }
    }


    /*** 授权接口*/
    public void authOauth() {
        RestProxy.getInstance().authOauth(new Observer<AuthOauthVo>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(AuthOauthVo authOauthVo) {
                Bundle bundle = new Bundle();
                bundle.putString("url", authOauthVo.data.oauthURL);
                bundle.putInt("type", 1);
                startActivityForResult(SignatureActivity.class, bundle, 2000);
            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
            }

            @Override
            public void onComplete() {
                dismissProgressDialog();
            }
        });
    }

    //查询是否已实名认证和签名
    public void querySignStatus() {
        showProgressDialog(mContext);
        RestProxy.getInstance().querySignStatus(BaseApplication.currentUserId, new Observer<UserInfoBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(UserInfoBean userInfoBean) {
                //realNameStatus为0 表示已实名认证  signatureImg不为空表示已签名
                if ("0".equals(userInfoBean.data.realNameStatus) && !TextUtils.isEmpty(userInfoBean.data.signatureImg)) {
                    queryOauthStatus();
                } else {
                    dismissProgressDialog();
                    SignatureDialog mSignatureDialog = SignatureDialog.newInstance();
                    mSignatureDialog.setmListener(new SignatureDialog.OnItemClickListener() {
                        @Override
                        public void onConfirm() {
                            startActivity(SignatureSettingActivity.class);
                        }

                        @Override
                        public void onCancel() {
                        }
                    });
                    mSignatureDialog.show(getSupportFragmentManager(), "mSignatureDialog");
                }
            }


            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
                dismissProgressDialog();
            }

            @Override
            public void onComplete() {

            }
        });
    }


    //患者自述相关
    private void getRegistrationDetail() {
        RestProxy.getInstance().getRegistrationDetail(BaseApplication.currentUserId, diagnoseId, new Observer<RegistrationDetailResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onNext(RegistrationDetailResponse registrationDetailResponse) {
                orderNumber = registrationDetailResponse.data.orderNumber;
                orderStatus = registrationDetailResponse.data.orderStatus;
                diagType = registrationDetailResponse.data.diagType;
                doctorName = registrationDetailResponse.data.doctorName;
                patientName = registrationDetailResponse.data.patientName;
                pAge = registrationDetailResponse.data.patientAge;
                createTime = registrationDetailResponse.data.createTime;
                acceptTime = registrationDetailResponse.data.acceptTime;
                BaseApplication.patientAvatar = registrationDetailResponse.data.patientAvatar;//患者头像
                doctorPicture = registrationDetailResponse.data.doctorPicture;
                chatFlag = registrationDetailResponse.data.flag;
                BaseApplication.patientSex = registrationDetailResponse.data.patientSex;
                patAccount = registrationDetailResponse.data.patAccount;
                tv_time.setText(createTime);
                startCountDownTimer(registrationDetailResponse.data.remainingTime);
                patientUserId = registrationDetailResponse.data.patientUserId;
                doctorUserId = registrationDetailResponse.data.doctorUserId;
                BaseApplication.patientUserId = patientUserId;
                BaseApplication.diagnoseId = diagnoseId;
                doctorId = registrationDetailResponse.data.doctorId;
                patientId = registrationDetailResponse.data.patientId;
                diagnoseFlag = registrationDetailResponse.data.diagnoseFlag;
                //ImageLoaderHelper.getInstance().GlideImageLoader( ChatActivity1.this, registrationDetailResponse.data.patientPicture, img_head, R.mipmap.img_default );
                businessType = registrationDetailResponse.data.businessType;
                if (registrationDetailResponse.data.businessType == UIConstants.GRAPHIC_TYPE_1) {
                    tv_title.setText(patientName + getString(R.string.string_consult_b));
                    btnPrescription.setVisibility(View.GONE);
                    btnHistory.setVisibility(View.GONE);
                } else if (registrationDetailResponse.data.businessType == UIConstants.GRAPHIC_TYPE_2) {
                    tv_title.setText(patientName + getString(R.string.string_referral_b));
                    btnPrescription.setVisibility(View.VISIBLE);
                    btnHistory.setVisibility(View.VISIBLE);
                }
                if (registrationDetailResponse.data.resultList != null) {
                    if (registrationDetailResponse.data.resultList.size() == 0) {
                        photo_recyclerView.setVisibility(View.GONE);
                    }
                    photoList.clear();
                    photoList.addAll(registrationDetailResponse.data.resultList);
                    adapter.notifyDataSetChanged();
                }
                if (UtilString.isEmpty(registrationDetailResponse.data.cardType)) {
                    tv_patient_detail.setText(registrationDetailResponse.data.patientName + "  " + registrationDetailResponse.data.patientSex + "  " + registrationDetailResponse.data.patientAge);
                } else if ("1".equals(registrationDetailResponse.data.cardType)) {
                    tv_patient_detail.setText(registrationDetailResponse.data.patientName + "  " + registrationDetailResponse.data.patientSex + "  " + registrationDetailResponse.data.patientAge + "  自费卡");
                } else {
                    tv_patient_detail.setText(registrationDetailResponse.data.patientName + "  " + registrationDetailResponse.data.patientSex + "  " + registrationDetailResponse.data.patientAge + "  社保卡");
                }
                tv_oneselfState.setText(registrationDetailResponse.data.oneselfState);

                tv_pass.setText(TextUtils.isEmpty(registrationDetailResponse.data.pastHistory) ? "无" : registrationDetailResponse.data.pastHistory);
                tv_allergy.setText(TextUtils.isEmpty(registrationDetailResponse.data.allergyHistory) ? "无" : registrationDetailResponse.data.allergyHistory);

                Log.e("状态---", diagType + "---" + oFlag);
                if (diagType == 3) {//云门诊，
                    remain_time_container.setVisibility(View.GONE);
                    if (oFlag == 303) {
                        if (isFromCloudList) {
                            dialogHuaWei = ProgressDialog.show(ChatActivity.this, "提示", "正在加载…", true, false, null);
                            //直接唤起视频
//                            new Handler().postDelayed(() -> startMeeting(), 500);
                        }
                        tv_close.setVisibility(View.GONE);
                        bottom.setVisibility(View.VISIBLE);

                    } else if (oFlag == 308) {//308 云门诊医生提交诊断意见或开方后
                        tv_close.setVisibility(View.GONE);
                        bottom.setVisibility(View.VISIBLE);
                        //能视频
                        btnAdd.setVisibility(View.VISIBLE);
                        btn_end.setVisibility(View.VISIBLE);
                    } else if (oFlag == 302) {
                        if (readyFlag == 1) {//已经报道
                            tv_close.setVisibility(View.GONE);
                            bottom.setVisibility(View.VISIBLE);//不能视频
                            btnAdd.setVisibility(View.GONE);
                        } else {//没有报到
                            tv_close.setVisibility(View.VISIBLE);
                            tv_close.setText("当前诊断未开始");
                            bottom.setVisibility(View.INVISIBLE);
                        }

                    } else if (oFlag == 304) {
                        tv_close.setVisibility(View.VISIBLE);
                        tv_close.setText("当前诊断已结束");
                        bottom.setVisibility(View.INVISIBLE);
                    } else {//待就诊
                        tv_close.setVisibility(View.VISIBLE);
                        tv_close.setText("当前诊断未开始");
                        bottom.setVisibility(View.INVISIBLE);
                    }
                } else if (diagType == 1) {//图文咨询
                    btn_end.setVisibility(View.VISIBLE);
                    if (registrationDetailResponse.data.flag == 2) {
                        //已经结束
                        tv_close.setText("当前诊断已结束");
                        tv_close.setVisibility(View.VISIBLE);

                        if (!TextUtils.isEmpty(orderNumber) && orderStatus != 50 && orderStatus != 60) {
                            bottom.setVisibility(View.VISIBLE);
                            btnAddPhoto.setVisibility(View.GONE);
                            btnVideo.setVisibility(View.GONE);
                            btnHistory.setVisibility(View.GONE);
                            btn_yuyin.setVisibility(View.GONE);
                            edt_content.setVisibility(View.GONE);
                            btnSend.setVisibility(View.GONE);
                            btnAdd.setVisibility(View.GONE);
                            yuyin.setVisibility(View.GONE);
                        } else {
                            bottom.setVisibility(View.INVISIBLE);
                        }
                        remain_time_container.setVisibility(View.GONE);
                        btn_end.setVisibility(View.INVISIBLE);
                    }
                }

                if (registrationDetailResponse.data.flag == 0) {
                    //是否结束咨询
                    if (businessType == UIConstants.GRAPHIC_TYPE_2) {
                        showReceiveReferralDialog();
                    } else {
                        showLogoutDialog2();
                    }
                    remain_time_container.setVisibility(View.GONE);

                }
                flag = registrationDetailResponse.data.flag;
                if (registrationDetailResponse.data.isPrescription == 0) {
                    findViewById(R.id.btn_prescription).setVisibility(View.GONE);
                }
                getMessageList();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(ChatActivity.this, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * 获取患者的账号信息
     */
    private void getPatientAccount() {
        RestProxy.getInstance().getPatientAccount(diagnoseId, UIConstants.XY_ACCOUNT_TYPE_1, new Observer<AccountRespnonse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(AccountRespnonse accountRespnonse) {
                videoAccount = accountRespnonse.data;
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void getMessageList() {
        RestProxy.getInstance().getChatList(diagnoseId, current + "", new Observer<ChatResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ChatResponse chatResponse) {
                messageList.clear();
                if (chatResponse.data.records != null) {
                    Collections.reverse(chatResponse.data.records);
                    messageList.addAll(chatResponse.data.records);
                    if (diagType == 1) {
                        if (chatFlag != 0) {
                            if (chatAdapter.getHeaderLayoutCount() == 0) {
                                chatAdapter.addHeaderView(LayoutInflater.from(mContext).inflate(R.layout.header_chat, chat_recyclerView, false));
                            }
                        }
                        if (chatFlag == 2) {
                            if (chatAdapter.getFooterLayoutCount() == 0) {
                                chatAdapter.addFooterView(LayoutInflater.from(mContext).inflate(R.layout.footer_chat, chat_recyclerView, false));
                            }
                        }
                    }
                }
                chatAdapter.setList(messageList);
                if (current == 1) {
                    chat_recyclerView.postDelayed(() -> {
                        nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
                    }, 1000);
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.onError(mContext, e);
                refreshLayout.finishRefresh(false);
            }

            @Override
            public void onComplete() {
                refreshLayout.finishRefresh(true);
            }
        });
    }

    @SuppressLint("CheckResult")
    private void checkPermission() {
        ApplyPermissionDialog applyPermissionDialog = ApplyPermissionDialog.newInstance("5", true);
        applyPermissionDialog.show(getSupportFragmentManager(), "applyPermissionDialog");
        applyPermissionDialog.setmListener(new ApplyPermissionDialog.OnItemClickListener() {

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onConfirm() {
                RxPermissions permissions = new RxPermissions(ChatActivity.this);
                permissions.request(VIDEOPERMISSIONS)
                        .subscribe(granted -> {
                            if (granted) {
                                startCall(videoAccount);
                            } else {
                                ToastUtil.showToast(mContext, "请同意语音和存储权限，否则功能无法使用");
                                startNotificationSetting(mContext);
                            }
                        });
            }

            @Override
            public void onCancel() {

            }
        });
    }

    public void startCall(String callNumber) {
        NemoSDK.getInstance().makeCall(callNumber, "", new MakeCallResponse() {
            @Override
            public void onCallSuccess() {
//                // 查询号码成功, 进入通话界面
                Intent callIntent = new Intent(ChatActivity.this, XyCallActivity.class);
                callIntent.putExtra("number", callNumber);
                startActivity(callIntent);
                LogUtil.e("onCallSuccess");
            }

            @Override
            public void onCallFail(String s, String s1) {
                LogUtil.e("onCallFail---" + s + "---" + s1);

            }
        });
    }

    /**
     * 结束诊断
     *
     * @time 2020/12/2 17:24
     */
    private void finishDiagnose() {
        if (diagType == 1) {//结束图文咨询
            RestProxy.getInstance().finishDiagnose(diagnoseId, patientUserId, new Observer<BaseResponse>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(BaseResponse baseResponse) {
                    mFinishDialog.dismiss();
                    finish();
                }

                @Override
                public void onError(Throwable e) {
                    ToastUtil.onError(ChatActivity.this, e);
                }

                @Override
                public void onComplete() {

                }
            });
        } else {
            RestProxy.getInstance().changeFlag(diagnoseId, "304", new Observer<BaseResponse>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(BaseResponse baseResponse) {
                    mFinishDialog.dismiss();
                    finish();
                }

                @Override
                public void onError(Throwable e) {
                    ToastUtil.onError(ChatActivity.this, e);
                }

                @Override
                public void onComplete() {

                }
            });
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        //data的返回值根据
        switch (requestCode) {
            case REQUEST_OPEN_CAMERA:
                uploadPic(imgPathOri);
                break;
            case REQUEST_GALLERY:
                if (data != null) {
                    Uri imgUriSel = data.getData();
                    String imgPathSel = UriUtils.formatUri(this, imgUriSel);
                    uploadPic(imgPathSel);
                }
                break;
            case 10000:
            case 10001:
                if (diagType == 1) {
                    getRegistrationDetail();
                }
                if (diagType == 3) {
                    finish();
                }
                break;
            case 2000:
                jump();
                break;
            default:
                break;
        }
    }


    /**
     * 创建原图像保存的文件
     */
    protected File createOriImageFile() throws IOException {
        @SuppressLint("SimpleDateFormat") String imgNameOri = "HomePic_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File pictureDirOri = new File(Objects.requireNonNull(getExternalFilesDir(Environment.DIRECTORY_PICTURES)).getAbsolutePath() + "/OriPicture");
        if (!pictureDirOri.exists()) {
            pictureDirOri.mkdirs();
        }
        File image = File.createTempFile(
                imgNameOri,         /* prefix */
                ".jpg",             /* suffix */
                pictureDirOri       /* directory */
        );
        imgPathOri = image.getAbsolutePath();
        return image;
    }

    private SelectPicModeDialog mSelectPicModeDialog = null;


    private void showSelectHeadPicDialog() {
        if (mSelectPicModeDialog == null) {
            // 初始化点击头像弹出的对话框
            mSelectPicModeDialog = SelectPicModeDialog.newInstance();
            mSelectPicModeDialog.setOnItemClickListener(new SelectPicModeDialog.OnItemClickListener() {
                @Override
                public void takePhotoClick() {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File oriPhotoFile = null;
                    try {
                        oriPhotoFile = createOriImageFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                        imgUriOri = Uri.fromFile(oriPhotoFile);
                    } else {
                        assert oriPhotoFile != null;
                        imgUriOri = FileProvider.getUriForFile(ChatActivity.this, UIConstants.FILE_PROVIDER_URI, oriPhotoFile);
                    }
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUriOri);
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    startActivityForResult(intent, REQUEST_OPEN_CAMERA);
                }

                @Override
                public void pickFromAlbumClick() {
                    @SuppressLint("IntentReset") Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(intent, REQUEST_GALLERY);
                }
            });
        }
        mSelectPicModeDialog.show(getSupportFragmentManager(), "SelectPicModeDialog");
    }


    private void uploadVideo(String imgPathSel, int time) {
        RestProxy.getInstance().uploadVideo(new File(imgPathSel), new Observer<PicUploadResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
//                dialog = ProgressDialog.show(ChatActivity1.this, "提示", "正在上传中…", true, false, null);
            }

            @Override
            public void onNext(PicUploadResponse picUploadResponse) {
                ChatResponse.Message message = new ChatResponse().new Message();
                SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
                String clientId = TimeUtil.getClientId();
                message.messageId = clientId;
                message.messageType = ChatResponse.AUDIO;
                message.fromType = ChatResponse.DOCTOR;
                message.flag = ChatResponse.SNEDING;
                message.content = picUploadResponse.data.shareUrl;
                message.src = picUploadResponse.data.shareUrl;
                message.sendTime = df.format(new Date());
                message.time = time;
                messageList.add(message);
                chatAdapter.addData(message);
                nestedScrollView.postDelayed(() -> {
                    nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);
                }, 500);
                WebSocket webSocket = new WebSocket.Builder().content(picUploadResponse.data.shareUrl).docId(doctorId).diagnoseId(diagnoseId).from(BaseApplication.currentUserId).to(patientUserId).picType("wav").msgType(2).eventFlag(1).clientId(clientId).time(time).build();
                EventBus.getDefault().postSticky(webSocket);
            }

            @Override
            public void onError(Throwable e) {
                dialog.dismiss();
                ToastUtil.onError(ChatActivity.this, e);
            }

            @Override
            public void onComplete() {
//                dialog.dismiss();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (timer != null) {
            timer.cancel();
        }
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
        BaseApplication.patientUserId = "";
        BaseApplication.diagnoseId = "";
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(WebSocket webSocket) {
        //eventFlag =0 接收消息
        if (webSocket.eventFlag == 0) {
            if (TextUtils.isEmpty(webSocket.diagnoseId)) {
                return;
            }
            if (TextUtils.isEmpty(webSocket.content)) {
                return;
            }

            if (webSocket.diagnoseId.equals(diagnoseId)) {
                if (webSocket.msgType != ChatResponse.PRESCRIPTION && webSocket.msgType != ChatResponse.CHECKOUT) {
                    ChatResponse.Message message = new ChatResponse().new Message();
                    message.messageId = TimeUtil.getClientId();
                    message.messageType = webSocket.msgType;
                    message.content = webSocket.content;
                    message.src = webSocket.src;
                    message.time = webSocket.time;
                    if (!TextUtils.isEmpty(webSocket.createTime)) {
                        //2023-10-24 09:11
                        message.sendTime = webSocket.createTime.substring(10);
                    }
                    message.fromType = 0;
                    messageList.add(message);
                    chatAdapter.addData(message);
                    nestedScrollView.postDelayed(() -> {
                        nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);
                    }, 500);
                } else {
                    //msgType==6代表处方消息
                    if (webSocket.msgType == 6) {
                        getPrescription(webSocket.preId);
                    } else {

                    }
                }
                WebSocket webSocket2 = new WebSocket();
                webSocket2.cmd = 24;
                webSocket2.diagnoseId = webSocket.diagnoseId;
                webSocket2.to = webSocket.to;
                webSocket2.msgId = webSocket.id;
                webSocket2.eventFlag = 4;
                EventBus.getDefault().postSticky(webSocket2);
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent2(WebSocketWrapper webSocket) {
        if (webSocket.cmd == UIConstants.WEBSOCKET_CMD_103) {
            ToastUtil.showToast(mContext, "患者结束咨询");
            finish();
        }
        if (webSocket.cmd == UIConstants.WEBSOCKET_CMD_105 || webSocket.cmd == UIConstants.WEBSOCKET_CMD_30) {
            isMeeting = false;
            finishMeeting();
        } else if (webSocket.cmd == UIConstants.WEBSOCKET_CMD_211 || webSocket.cmd == UIConstants.WEBSOCKET_CMD_212) {
            current = 1;
            messageList.clear();
            getMessageList();
        } else if (webSocket.code == 10000 || webSocket.code == 10001) {
            for (int i = messageList.size() - 1; i >= 0; i--) {
                if (!TextUtils.isEmpty(messageList.get(i).messageId) && messageList.get(i).messageId.equals(webSocket.clientId)) {
                    messageList.get(i).flag = 0;
                    chatAdapter.notifyItemChanged(i + chatAdapter.getHeaderLayoutCount(), ChatAdapter.PLAYLOAD_SENDSUCCESS);
                    break;
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBillingEvent(BillingStatusChangeEvent event) {
        refreshLayout.autoRefresh();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            finish();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    /**
     * 查询处方详情
     *
     * @time 2020/8/26 16:52
     */
    private void getPrescription(String preId) {
        RestProxy.getInstance().getPrescription2(preId, new Observer<Prescription2Response>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Prescription2Response prescriptionResponse) {
                ChatResponse.Message message = new ChatResponse().new Message();
                message.messageId = TimeUtil.getClientId();
                message.messageType = ChatResponse.PRESCRIPTION;
                message.flag = ChatResponse.SNEDSUCCESS;
                message.fromType = ChatResponse.DOCTOR;
                message.prescription = prescriptionResponse.data;
                messageList.add(message);
                chatAdapter.addData(message);
                nestedScrollView.postDelayed(() -> {
                    nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);
                }, 500);
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * 结束会议
     *
     * @time 2020/8/1 18:46
     */
    private void finishMeeting() {
        if (TextUtils.isEmpty(BaseApplication.conferenceID)) {
            return;
        }
        RestProxy.getInstance().finishMeeting(patientUserId, diagnoseId, BaseApplication.currentUserId, BaseApplication.conferenceID, "0", new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                BaseApplication.conferenceID = "";
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    @Override
    protected void onNewIntent(Intent intent) {
        Log.e("onnewintent", "onnewintent");
        //移动视频传过来的参数
        long userid = intent.getLongExtra("userid", 0);
        Log.e("", "onNewIntent: " + userid);
//        if (userid != 0) {
//            checkPermissionAndShow(userid);
//        }
        super.onNewIntent(intent);
    }

    private void acceptDiagnose(final int status) {
        RestProxy.getInstance().acceptDiagnose(diagnoseId, status + "", new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                if (status == 0) {
                    finish();
                }
                current = 1;
                getRegistrationDetail();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(ChatActivity.this, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    protected void checkPermissionAndShow(long userid) {
        // 检查是否已经授权
        if (FloatWinPermissionCompat.getInstance().check(this)) {
            Intent intent = new Intent(ChatActivity.this, FloatingService.class);
            intent.putExtra("userid", userid);
            if (userid == 0) {
                stopService(intent);
            } else {
                startService(intent);
            }
        } else {
            // 授权提示
            new AlertDialog.Builder(this).setTitle("悬浮窗权限未开启")
                    .setMessage("你的手机没有授权" + this.getString(R.string.app_name) + "获得悬浮窗权限，视频悬浮窗功能将无法正常使用")
                    .setPositiveButton("开启", (dialog, which) -> {
                        // 显示授权界面
                        try {
                            FloatWinPermissionCompat.getInstance().apply(ChatActivity.this);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    })
                    .setNegativeButton("取消", null).show();
        }
    }

    private CountDownTimer timer;

    private void startCountDownTimer(String remainPayTime) {
        if (TextUtils.isEmpty(remainPayTime) || Long.parseLong(remainPayTime) < 0) {
            return;
        }
        Log.e("倒计时===", remainPayTime);
        final int parseInt = Integer.parseInt(remainPayTime);
        timer = new CountDownTimer(parseInt, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                tv_remain_time.setText(millisUntilFinished / 60000 / 60 + "时" + millisUntilFinished / 60000 % 60 + "分" + (millisUntilFinished / 1000) % 60 + "秒");
            }

            @Override
            public void onFinish() {
            }
        };
        timer.start();
    }

    private void uploadPic(String imgPathSel) {
        dialog = ProgressDialog.show(ChatActivity.this, "提示", "正在上传中…", true, false, null);
        UploadPictureUtil.uploadPic("9", "92", imgPathSel, "1", new UploadPictureUtil.UploadCallBack() {
            @Override
            public void success(PicUploadResponse.ImageBean imageBean) {
                try {
                    runOnUiThread(() -> {
                        checkServiceRunning(mContext);
                        dialog.dismiss();
                        ChatResponse.Message message = new ChatResponse().new Message();
                        @SuppressLint("SimpleDateFormat")
                        SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
                        message.messageType = 1;
                        String clientId = TimeUtil.getClientId();
                        message.messageId = clientId;
                        message.fromType = 1;
                        message.flag = 1;
                        message.content = imageBean.shareThumbnailUrl;
                        message.src = imageBean.shareUrl;
                        message.sendTime = df.format(new Date());
                        messageList.add(message);
                        chatAdapter.addData(message);
                        nestedScrollView.postDelayed(() -> {
                            nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);
                        }, 500);
                        WebSocket webSocket = new WebSocket.Builder().content(imageBean.shareThumbnailUrl).docId(doctorId).diagnoseId(diagnoseId).from(BaseApplication.currentUserId).to(patientUserId).picType("jpeg").src(imageBean.shareUrl).msgType(1).eventFlag(1).clientId(clientId).build();
                        EventBus.getDefault().postSticky(webSocket);
                    });

                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    dialog.dismiss();
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }
            }

            @Override
            public void fail(Throwable e) {
                dialog.dismiss();
            }
        });
    }

    @SuppressLint("CheckResult")
    private void checkVoicePermission() {
        ApplyPermissionDialog applyPermissionDialog = ApplyPermissionDialog.newInstance("4", true);
        applyPermissionDialog.show(getSupportFragmentManager(), "applyPermissionDialog");
        applyPermissionDialog.setmListener(new ApplyPermissionDialog.OnItemClickListener() {

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onConfirm() {
                RxPermissions permissions = new RxPermissions(ChatActivity.this);
                permissions.request(VOICEPERMISSIONS)
                        .subscribe(granted -> {
                            if (granted) {
                                switchTextAndAudio();
                            } else {
                                ToastUtil.showToast(mContext, "请同意语音和存储权限，否则功能无法使用");
                                startNotificationSetting(mContext);
                            }
                        });
            }

            @Override
            public void onCancel() {

            }
        });
    }

    @SuppressLint("CheckResult")
    private void getPermission() {
        ApplyPermissionDialog applyPermissionDialog = ApplyPermissionDialog.newInstance("3", true);
        applyPermissionDialog.show(getSupportFragmentManager(), "applyPermissionDialog");
        applyPermissionDialog.setmListener(new ApplyPermissionDialog.OnItemClickListener() {

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onConfirm() {
                RxPermissions permissions = new RxPermissions(ChatActivity.this);
                permissions.request(PERMISSIONS)
                        .subscribe(granted -> {
                            if (granted) {
                                //已经打开权限
                                showSelectHeadPicDialog();
                            } else {
                                ToastUtil.showToast(mContext, "请同意相册和存储权限，否则功能无法使用");
                                startNotificationSetting(mContext);
                            }
                        });
            }

            @Override
            public void onCancel() {

            }
        });
    }

    private void showLogoutDialog() {
        mFinishDialog = FinishDialog.newInstance();
        mFinishDialog.show(getSupportFragmentManager(), "mFinishDialog");
        mFinishDialog.setmListener(new FinishDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                finishDiagnose();
            }

            @Override
            public void onCancel() {
                mFinishDialog.dismiss();
            }
        });
    }

    private void showLogoutDialog2() {
        mFinish2Dialog = Finish2Dialog.newInstance();
        mFinish2Dialog.show(getSupportFragmentManager(), "mFinish2Dialog");
        mFinish2Dialog.setmListener(new Finish2Dialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                acceptDiagnose(1);
                mFinish2Dialog.dismiss();
            }

            @Override
            public void onCancel() {
                acceptDiagnose(0);
                mFinish2Dialog.dismiss();
            }
        });
    }

    private void showReceiveReferralDialog() {
        receiveReferralDialog = ReceiveReferralDialog.newInstance();
        receiveReferralDialog.show(getSupportFragmentManager(), "ReceiveReferralDialog");
        receiveReferralDialog.setmListener(new ReceiveReferralDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                acceptDiagnose(1);
                receiveReferralDialog.dismiss();
            }

            @Override
            public void onCancel() {
                acceptDiagnose(0);
                receiveReferralDialog.dismiss();
            }
        });
    }
}
